package com.sdu.game.websocket;

import com.sdu.game.wbr.game_play.ActFunction;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

//用户点击进入房间:使用webSocket,传入用户id，返回分配的房间信息,此处的socket列表和gammroom准备阶段的不一样
@ServerEndpoint("/webSocket/play/{sid}")
@Component
public class GamePlay {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。

    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    //保存用户的投票信息
    private static ConcurrentHashMap<String, String> uservot = new ConcurrentHashMap<>();

    public static ConcurrentHashMap<String, String> getUservot() {
        return uservot;
    }

    public static void setUservot(ConcurrentHashMap<String, String> uservot) {
        GamePlay.uservot = uservot;
    }

    ConcurrentHashMap<String,Session> sessionList=new ConcurrentHashMap<>();

    private Session session;
    private String userId="";

    public static ConcurrentHashMap<String, Session> getSessionPools() {
        return sessionPools;
    }

    public static void setSessionPools(ConcurrentHashMap<String, Session> sessionPools) {
        GamePlay.sessionPools = sessionPools;
    }

    //发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
//                System.out.println("发送数据：" + message);
                session.getBasicRemote().sendText(message);
            }
        }
    }
    //给指定用户发送信息
    public void sendInfo(String userName, String message){
        Session session = sessionPools.get(userName);
        try {
            sendMessage(session, message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void sendInfouser(String userName, String user){
        Session session = sessionPools.get(userName);
        try {
            if(session != null){
                synchronized (session) {
//                System.out.println("发送数据：" + message);
                    session.getBasicRemote().sendText(user);
                    System.out.println("类发送成功");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "sid") String userName){
        //使用用户id来作为session的唯一判断标准和数据库中的房间中的用户对应
        System.out.println(userName);
        Session sessiont= sessionPools.get(userName);

        //判断用户是否已经存在，同一人不能同时加入两个房间
        try {
            if(sessiont == null){
                synchronized (session) {
//                System.out.println("发送数据：" + message);
                    System.out.println("ssssssssssssssssssssssss");
                    sessionPools.put(userName, session);
                    addOnlineCount();//在线人数
//                    session.getBasicRemote().sendText(user);
//                    System.out.println("类发送成功");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        //建立连接后开始游戏

        System.out.println("scccccccccccccccccccccccccccccccccc");

        uservot.put("1","4");
        uservot.put("2","5");

        System.out.println(uservot.get("2"));//得到该用户id投票的结果







        //可使用hasmap构建数据
        String Data_user="用户数据收取成功";//假想用户数据



        //使用用户Id列表在session列表中找出对应的session

        ArrayList<String> idlist=new ArrayList<>();//存储和该用户同房间的用户id
        //对每个用户发送消息

        idlist.add(userName);

        for(int i=0;i<idlist.size();i++){
            Session sessiond= sessionPools.get(userName);
            try {
                sendMessage(sessiond, Data_user);
            } catch(Exception e){
                e.printStackTrace();
                continue;
            }

        }


        System.out.println(sessionPools.toString());

//        System.out.println(userName + "加入webSocket！当前人数为" + onlineNum);
//        System.out.println(session.getId());
        try {
            sendMessage(session, "欢迎" + userName + "加入连接！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //关闭连接时调用
    //当玩家退出时需要将玩家连接关闭的同时，将其从数据库中删除
    @OnClose
    public void onClose(@PathParam(value = "sid") String userName){
        sessionPools.remove(userName);
        subOnlineCount();

        //数据库操作，userId，在玩家表中找到该玩家得到房间号，然后将玩家删除，同时在房间表中将用户删除

        System.out.println(userName + "断开webSocket连接！当前人数为" + onlineNum);
    }

    ActFunction af = new ActFunction();

    //收到客户端信息
    //客户端接收用户投票信息存入uservot中
    @OnMessage
    public void onMessage(String message) throws IOException{
        message = "客户端：" + message + ",已收到";

        System.out.println("message : "+message);

        //加入到uservot中
        String[] str_list = message.split(":");
        System.out.println("user : "+str_list[0]);

        String order = str_list[1].split(",")[0];
        System.out.println(order);
        if(order.equals("1")){
            // 狼人投票信息实时反馈
            String result =  af.WolfVoteAction(str_list[1].split(",")[1]);
            System.out.println("狼人实时反馈");
            System.out.println(result);

        }
        else{
            uservot.put(str_list[0],str_list[1]);
        }

        System.out.println(message);
        for (Session session: sessionPools.values()) {
            try {
                sendMessage(session, message);
            } catch(Exception e){
                e.printStackTrace();
                continue;
            }
        }
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
        System.out.println("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }

}